package bscorp.appbase.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Date;

import bscorp.appbase.R;
import bscorp.appbase.bmo.UserBmo;
import bscorp.appbase.model.User;
import bscorp.appbase.view.SmoothCheckBox;
import utils.CheckNetwork;
import utils.Constants;
import utils.ValidateUserInfo;

/**
 * Created by AndreBTS on 20/08/2015.
 */
public class RegisterActivity extends Activity implements View.OnClickListener {
    EditText edit_nome, edit_email, edit_password, edit_phone;
    TextView txt_alreadyHave;
    Button btn_registrar;
    SmoothCheckBox cb_other_gender_man;
    SmoothCheckBox cb_other_gender_woman;
    SmoothCheckBox cb_other_type_user;
    SmoothCheckBox cb_other_type_work;
    private CreateUserTask mCreateTask = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_account);

        String email;
        if (savedInstanceState == null) {
            Bundle extras = getIntent().getExtras();
            email = extras == null ? "" : extras.getString(Constants.TAG_EMAIL);
        } else {
            email = savedInstanceState.getString(Constants.TAG_EMAIL);
        }

        edit_nome = (EditText) findViewById(R.id.edit_nome);
        edit_phone = (EditText) findViewById(R.id.edit_phone);
        cb_other_gender_man = (SmoothCheckBox) findViewById(R.id.cb_other_gender_man);
        cb_other_gender_man.setChecked(true);
        cb_other_gender_man.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkBoxSwitch(cb_other_gender_man, cb_other_gender_woman);
            }
        });
        cb_other_gender_woman = (SmoothCheckBox) findViewById(R.id.cb_other_gender_woman);
        cb_other_gender_woman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkBoxSwitch(cb_other_gender_woman, cb_other_gender_man);
            }
        });
        cb_other_type_user = (SmoothCheckBox) findViewById(R.id.cb_other_type_user);
        cb_other_type_user.setChecked(true);
        cb_other_type_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkBoxSwitch(cb_other_type_user, cb_other_type_work);
            }
        });
        cb_other_type_work = (SmoothCheckBox) findViewById(R.id.cb_other_type_work);
        cb_other_type_work.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkBoxSwitch(cb_other_type_work, cb_other_type_user);
            }
        });
        edit_email = (EditText) findViewById(R.id.edit_email);
        edit_email.setText(email);
        edit_password = (EditText) findViewById(R.id.edit_password);
        txt_alreadyHave = (TextView) findViewById(R.id.txt_already_have);
        txt_alreadyHave.setOnClickListener(this);

        btn_registrar = (Button) findViewById(R.id.btn_register);
        btn_registrar.setOnClickListener(this);

        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    public void checkBoxSwitch(SmoothCheckBox boxA, SmoothCheckBox boxB) {
        if (boxA.isChecked()) {
            boxA.setChecked(false, true);
            boxB.setChecked(true, true);
        } else {
            boxA.setChecked(true, true);
            boxB.setChecked(false, true);
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid email, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    public void attemptCreate() {
        // Store values at the time of the login attempt.
        String name = edit_nome.getText().toString();
        String email = edit_email.getText().toString();
        String password = edit_password.getText().toString();
        String phone = edit_phone.getText().toString();

        boolean cancel = false;
        View focusView = null;

        ValidateUserInfo validate = new ValidateUserInfo();

        // Check for a valid email address.
        if (TextUtils.isEmpty(name)) {
            edit_nome.setError(getString(R.string.error_field_required));
            focusView = edit_nome;
            cancel = true;
        } else if (TextUtils.isEmpty(email)) {
            edit_email.setError(getString(R.string.error_field_required));
            focusView = edit_email;
            cancel = true;
        } else if (TextUtils.isEmpty(phone)) {
            edit_phone.setError(getString(R.string.error_field_required));
            focusView = edit_phone;
            cancel = true;
        } else if (TextUtils.isEmpty(password)) {
            edit_password.setError(getString(R.string.error_field_required));
            focusView = edit_password;
            cancel = true;
        } else if (!validate.isPasswordValid(password)) {
            edit_password.setError(getString(R.string.error_invalid_password));
            focusView = edit_password;
            cancel = true;
        }

        if (cancel) {
            focusView.requestFocus();
        } else {
            mCreateTask = new CreateUserTask(name, email, password, phone, cb_other_gender_man.isChecked(), cb_other_type_user.isChecked());
            mCreateTask.execute((Void) null);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_register:
                attemptCreate();
                break;
            case R.id.txt_already_have:
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
                break;
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class CreateUserTask extends AsyncTask<Void, Void, Boolean> {
        private final String mName;
        private final String mUser;
        private final String mPassword;
        private final String mPhone;
        private final boolean mIsMan;
        private final boolean mIsUser;


        CreateUserTask(String name, String user, String password, String phone, boolean isMan, boolean isUser) {
            mName = name;
            mUser = user;
            mPhone = phone;
            mPassword = password;
            mIsMan = isMan;
            mIsUser = isUser;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            User user = new User();
            user.setName(mName);
            user.setLogin(mUser);
            user.setPhone(mPhone);
            user.setPassword(mPassword);
            user.setGender(mIsMan ? "man" : "woman");
            user.setType(mIsUser ? User.TYPE_USER : User.TYPE_WORKER);
            user.setRegisterTime(new Date());
            UserBmo userBmo = new UserBmo();
            return userBmo.saveUserInfo(user);
        }

        @Override
        protected void onPostExecute(final Boolean success) {
            mCreateTask = null;
            CheckNetwork checkNetwork = new CheckNetwork();
            if (checkNetwork.isConnected(RegisterActivity.this) && success) {
                Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                onBackPressed();
            } else {
                Toast.makeText(RegisterActivity.this, "注册失败，账号已经存在", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected void onCancelled() {
            mCreateTask = null;
        }
    }

    @Override
    public void onBackPressed() {
        startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
        finish();
    }
}
